import { normalLoginApi, authLoginApi, logOut, checkLogin, doRegist } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import Cookies from 'js-cookie'

const user = {
  state: {
    token: getToken(),
    name: '',
    isLogin: false,
    userCode: '',
    roles: []
  },

  mutations: {
    IS_LOGIN: (state, token) => {
      state.isLogin = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_CODE: (state, avatar) => {
      state.userCode = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    NormalLogin({ commit }, userInfo) {
      userInfo.userName = userInfo.userName.trim()
      return new Promise((resolve, reject) => {
        normalLoginApi(userInfo).then(response => {
          commit('IS_LOGIN', true)
          commit('SET_NAME', Cookies.get('un'))
          commit('SET_CODE', Cookies.get('uc'))
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    AuthLogin({ commit }, userInfo) {
      userInfo.userName = userInfo.userName.trim()
      return new Promise((resolve, reject) => {
        authLoginApi(userInfo).then(response => {
          commit('IS_LOGIN', true)
          commit('SET_NAME', Cookies.get('un'))
          commit('SET_CODE', Cookies.get('uc'))
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    Regist({ commit }, userInfo) {
      userInfo.userName = userInfo.userName.trim()
      return new Promise((resolve, reject) => {
        doRegist(userInfo).then(response => {
          commit('IS_LOGIN', true)
          commit('SET_NAME', Cookies.get('un'))
          commit('SET_CODE', Cookies.get('uc'))
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 检查是否登陆了
    CheckLogin({ commit, state }) {
      return new Promise((resolve, reject) => {
        checkLogin().then(response => {
          if (response.code == 0) {
            commit('IS_LOGIN', true)
            commit('SET_NAME', Cookies.get('un'))
            commit('SET_CODE', Cookies.get('uc'))
          } else {
            commit('IS_LOGIN', false)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logOut().then(() => {
          commit('IS_LOGIN', false)
          commit('SET_NAME', '')
          commit('SET_CODE', '')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
